//
//  DynamicContentView.m
//  WeCommunity
//
//  Created by mac on 2017/6/14.
//  Copyright © 2017年 lzy. All rights reserved.
//

#import "DynamicContentView.h"

//字体间距 9以下有些字体间没有行间距
#define DYNAMIC_Spacing  ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0 ? 0.0 : 6.0)

@interface DynamicContentView ()

@property (nonatomic,strong) UIMenuController * menuController;
@property (nonatomic,strong) UIMenuItem * textCopyMenuItem;

@end

@implementation DynamicContentView

-(instancetype)init
{
    if (self = [super init]) {
        //长按手势
        UILongPressGestureRecognizer * longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(processGesture:)];
        [self addGestureRecognizer:longPress];
    }
    return self;
}

-(BOOL)canBecomeFirstResponder{
    return YES;
}



-(YYLabel *)contentLabel
{
    if (!_contentLabel) {
        _contentLabel = [[YYLabel alloc] init];
        _contentLabel.font = PFR_FONT(14);
        _contentLabel.textColor = [UIColor blackColor];
        [self addSubview:_contentLabel];
    }
    return _contentLabel;
}

-(UIButton *)moreButton
{
    if (!_moreButton) {
        _moreButton = [[UIButton alloc] init];
        [_moreButton setTitle:KNSLocal(@"showMore") forState:UIControlStateNormal];
        [_moreButton setTitle:KNSLocal(@"hiddenMore") forState:UIControlStateSelected];
        [_moreButton setTitleColor:[UIColor colorWithHex:0x576b95 alpha:1.0] forState:UIControlStateNormal];
        [_moreButton setTitleColor:[UIColor colorWithHex:0xe8e8e9 alpha:1.0] forState:UIControlStateHighlighted];
        _moreButton.titleLabel.font = PFR_FONT(12);
        [_moreButton addTarget:self action:@selector(clickMoreButton:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_moreButton];
        
    }
    return _moreButton;
}

-(DynamicImageView *)dynamicImageView
{
    if (!_dynamicImageView) {
        _dynamicImageView  = [[DynamicImageView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.moreButton.frame), CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) - CGRectGetMaxY(self.moreButton.frame))];
        [self addSubview:_dynamicImageView];
    }
    return _dynamicImageView;
}


-(void)creatDynamicContentViewWithModel:(DynamicModel * )model
{
    self.dynamicModel = model;
    
    //设置内容
    [self creatDynamicTitleWithModel:model];
    
    //设置图片
    self.dynamicImages =  model.imageList;
    
}

-(void)setDynamicImages:(NSArray *)dynamicImages
{
    if(dynamicImages.count > 0){
        self.dynamicImageView.hidden = NO;
        self.dynamicImageView.frame = CGRectMake(0, CGRectGetMaxY(self.moreButton.frame), CGRectGetWidth(self.bounds), CGRectGetHeight(self.bounds) - CGRectGetMaxY(self.moreButton.frame) );
        self.dynamicImageView.dynamicModel = self.dynamicModel;
    }else{
        self.dynamicImageView.hidden = YES;
        self.dynamicImageView.frame = CGRectMake(0, 0, 0, 0);
    }
}

-(void)creatDynamicTitleWithModel:(DynamicModel *)model
{
    if (model.content.length > 0) {
        self.contentLabel.hidden = NO;
    }else{
        self.contentLabel.hidden = YES;
        self.contentLabel.frame = CGRectMake(0, 0, 0, 0);
        self.moreButton.hidden = YES;
        self.moreButton.frame = CGRectMake(0,0, 0, 0);
        
        return;
    }
    
    self.contentLabel.frame = CGRectMake(0, 0, CGRectGetWidth(self.bounds), CGFLOAT_MAX);
    self.contentLabel.text = model.content;
    self.contentLabel.attributedText = [self addRichTextWithString:model.content urlColor:nil font:PFR_FONT(14)];
    self.contentLabel.lineBreakMode = NSLineBreakByCharWrapping; //换行格式
    if (_dynamicModel.showAlltext) {
        self.contentLabel.numberOfLines = 0;
        self.moreButton.selected = YES;
    }else{
        self.contentLabel.numberOfLines = 4;
        self.moreButton.selected = NO;
    }
    [self.contentLabel sizeToFit];
    
    NSMutableParagraphStyle *paraStyle = [[NSMutableParagraphStyle alloc] init];
    paraStyle.lineSpacing = DYNAMIC_Spacing; //设置行间距
    NSDictionary * attriDic = @{NSFontAttributeName:self.contentLabel.font, NSParagraphStyleAttributeName:paraStyle};
    
    CGSize oneLineSize = [@"测试文字" boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX)
                                               options:NSStringDrawingTruncatesLastVisibleLine |
                                                        NSStringDrawingUsesLineFragmentOrigin |
                                                            NSStringDrawingUsesFontLeading
                                            attributes:attriDic
                                               context:nil].size;
    
    CGFloat  fourLineHeight = oneLineSize.height * 4 + 3 * DYNAMIC_Spacing;
    
    CGSize textSize = [self.contentLabel.text boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX)
                                                             options:NSStringDrawingTruncatesLastVisibleLine |
                                                                        NSStringDrawingUsesLineFragmentOrigin |
                                                                            NSStringDrawingUsesFontLeading
                                                          attributes:attriDic
                                                             context:nil].size;
    
    CGFloat textHeight = textSize.height;
    
    if (textHeight > fourLineHeight) {
        self.moreButton.hidden = NO;
        attriDic = @{NSFontAttributeName:self.moreButton.titleLabel.font};
        CGSize moreBtnWidth = [KNSLocal(@"showMore") boundingRectWithSize:CGSizeMake(CGRectGetWidth(self.bounds), CGFLOAT_MAX)
                                                   options:NSStringDrawingTruncatesLastVisibleLine |
                              NSStringDrawingUsesLineFragmentOrigin |
                              NSStringDrawingUsesFontLeading
                                                attributes:attriDic
                                                   context:nil].size;
        self.moreButton.frame = CGRectMake(0,CGRectGetMaxY(self.contentLabel.frame) , moreBtnWidth.width, 25);
    }else{
        self.moreButton.hidden = YES;
        self.moreButton.frame = CGRectMake(0,CGRectGetMaxY(self.contentLabel.frame), 0, 0);
    }
}
#pragma mark -  显示更多
-(void)clickMoreButton:(UIButton *)sender
{
    if (self.delegate) {
        sender.selected = !sender.selected;
        if (!_dynamicModel.showAlltext) {
            _dynamicModel.showAlltext = YES;
        }else{
            _dynamicModel.showAlltext = NO;
        }
        [self.delegate  isShowMoreContent:_dynamicModel.showAlltext sender:sender];
    }
}

#pragma mark - 手势
- (void) processGesture:(UISwipeGestureRecognizer *)gesture
{
    if ([gesture isKindOfClass:[UILongPressGestureRecognizer class]]) {
        if (self.dynamicModel.content.length == 0) {
            return;
        }
        // 长按手势
        if (gesture.state == UIGestureRecognizerStateEnded  || gesture.state ==UIGestureRecognizerStateChanged) {
            //sender.state ==UIGestureRecognizerStateChanged这个限制不添加也不影响执行一次的功能，只是若长按住View不放手，一直在上面拖动的话，会一直响应下面else
            return;
        }else {
            //这里长按一次只会进入一次
            
            [self becomeFirstResponder];
            
            if (self.menuController == nil) {
                self.menuController = [UIMenuController sharedMenuController];
            }
            if (self.textCopyMenuItem == nil) { //复制
                self.textCopyMenuItem = [[UIMenuItem alloc] initWithTitle:KNSLocal(@"Copy") action:@selector(copyMenuAction:)];
            }
            
            [self.menuController setMenuItems:@[_textCopyMenuItem]];
            [self.menuController setTargetRect:self.frame inView:self.superview];
            [self.menuController setMenuVisible:YES animated:YES];
        }
    }
}

#pragma mark - 复制
- (void)copyMenuAction:(id)sender
{
    [UITool textCopyWithString:self.dynamicModel.content];
}

#pragma mark - 设置富文本
-(NSAttributedString *)addRichTextWithString:(NSString *)string
                                    urlColor:(UIColor *)urlColor
                                        font:(UIFont *)font
{
    if (!urlColor) {
        urlColor = [UIColor colorWithHex:0x3478f6 alpha:1.0];
    }
    NSMutableAttributedString * mutStr = [[NSMutableAttributedString alloc] initWithString:string];
    mutStr.yy_font = font;
    mutStr.yy_color = [UIColor blackColor];
    
    //识别链接的正则
    NSString *regulaStr = @"((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)|(www.[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&*+?:_/=<>]*)?)";
    
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:regulaStr
                                                                           options:NSRegularExpressionCaseInsensitive
                                                                             error:&error];
    NSArray *arrayOfAllMatches = [regex matchesInString:string options:0 range:NSMakeRange(0, [string length])];
    NSMutableArray *urlArr = [[NSMutableArray alloc]init];
    NSMutableArray *rangeArr = [[NSMutableArray alloc]init];
    
    for (NSTextCheckingResult * match in arrayOfAllMatches)
    {
        NSString* substringForMatch;
        substringForMatch = [string substringWithRange:match.range];
        [urlArr addObject:substringForMatch];
        
    }
    for (NSString *str in urlArr) {
        [rangeArr addObject:[self rangesOfString:str inString:string]];
    }
    
    int i = 0;
    for(NSValue *value in rangeArr)
    {
        NSRange range=[value rangeValue];
        /**
         *处理链接
         */
        [mutStr yy_setTextHighlightRange:range
                                   color:urlColor
                         backgroundColor:[UIColor colorWithWhite:0.0 alpha:0.2]
                               tapAction:^(UIView *containerView, NSAttributedString *text, NSRange range, CGRect rect){
                                   if ([self.delegate respondsToSelector:@selector(processCommunityUrlLink:)]) {
                                       [self.delegate processCommunityUrlLink:urlArr[i]];
                                   }
                               }];
        i++;
    }
    
    
    return mutStr;
}

//获取查找字符串在母串中的NSRange
- (NSValue *)rangesOfString:(NSString *)searchString inString:(NSString *)str {
    
    NSRange searchRange = NSMakeRange(0, [str length]);
    
    NSRange range;
    
    if ((range = [str rangeOfString:searchString options:0 range:searchRange]).location != NSNotFound) {
        searchRange = NSMakeRange(NSMaxRange(range), [str length] - NSMaxRange(range));
    }
    return [NSValue valueWithRange:range];
}



@end
